from flask import Blueprint,request,Response
from concurrent.futures import ThreadPoolExecutor
import time
from control import *
from instance.settings import FeeRate


class Costor:
	def __init__(self,db):
		self.flag=True
		# 连接数据库
		self.db=db
	
	#以秒为单位计算每一台从机的能量及消费金额并更新到从机状态
	def run(self):
		time_stamp = 1
		while self.flag:
			status={'id':[],'speed':[], 'amount':[]}#存放每一台从控机的状态信息

			# 选出每一台从控机的状态信息
            # 从状态表中选出每一台从控机的id,speed,amount
			pre_status = self.db.select_status()
			for sta in pre_status:
				status['id'].append(sta[0])
				status['speed'].append(sta[1])
				status['amount'].append(sta[2])

			#计算每一台从控机的单位时间消费金额
			for num in range(len(status['id'])):
				if status['speed'][num]==1:#上一次request是低速风，按每分钟1元1度
					cost = FeeRate*1/180
				elif status['speed'][num]==3:#上一次request是高速风，按每分钟1.3标准功率计算能量
					cost = FeeRate*1/60
				else:#上一次request是中速风，按每分钟1.0标准功率计算能量（默认是中速风）
					cost = FeeRate*1/120

				#更新从控机状态
				self.db.status_fee(id,cost)
				# self.cursor.execute("update status set amount=amount+%s where id=%s"%(cost,status['id'][num]))

			time.sleep(time_stamp) #为实现time_stamp秒计算一次

	def exit(self):
		self.flag=False#为退出计算
		self.db.close()


cost = Blueprint('cost', __name__)
costor = Costor()
cost_executor = ThreadPoolExecutor(1)

@cost.route("/open")
def open_cost():
    costor.flag = True
    cost_executor.submit(costor.run)
    return Response('ok',200)

@cost.route("/close")
def close_cost():
    costor.exit()
    return Response('ok',200)